class MessagesController < ApplicationController
  include AuthenticatedSystemBrowse
  
  before_filter :login_required, :only => [ :index, :send, :show, :recvbox, :sendbox, :deliver, :batch_delete, :delete ]
  
  def index
    @recvs = find_messages_by_box('r')
    @sends = find_messages_by_box('s')
    
    @unread_messages_num = unread_messages_num()
    @page_title = '消息'
  end
  
  def deliver
    @user = User.find_by_login(params[:id])
    @page_title = '发送消息'
    return unless request.post?
    if @user.login != current_user.login
	Message.transaction do
            @message = Message.new
            @message.title = params[:message][:title]
            @message.content = params[:message][:content]
            @message.save!
            r_user_message = UserMessage.new(:user => @user, :message => @message, :from_id => current_user.id, :to_id => @user.id, :box => 'r', :is_read => 'f')
            s_user_message = UserMessage.new(:user => current_user, :message => @message, :from_id => current_user.id, :to_id => @user.id, :box => 's', :is_read => 't')
            r_user_message.save!
            s_user_message.save!
        end
    end
    flash[:notice] = '消息已发送.'
    redirect_to sendbox_messages_url    
    rescue ActiveRecord::RecordInvalid
    render :action => 'deliver'
  end
  
  
  def batch_delete
    messages_to_deleted = params[:to_be_deleted]
	if !messages_to_deleted.empty?
	  messages_to_deleted.each do |message_id, do_it|
        if do_it == "yes"
          message = current_user.messages.find(:first, :conditions => ["messages.id = ?", message_id])
          delete_message(message)
        end
      end
    end
	redirect_to :back
  end
  
  def destroy
	message = current_user.messages.find(:first, :conditions => ["messages.id = ?", params[:id]])
	delete_message(message)
	redirect_back_or_default messages_url
  end
  
  def show
    @message = current_user.messages.find(:first, :conditions => ["messages.id = ?", params[:id]])
    misc = find_message_by_id(params[:id])
    if misc.nil?
      #error_page("你未登陆或者你无权查看该邮件")
      raise ActiveRecord::RecordNotFound
    else
      @user = User.find(misc.from_id)
      @touser = User.find(misc.to_id)
      if @user != current_user && @touser != current_user
        redirect_to :back
      elsif misc.box == 'r'
        Message.transaction do
          #current_user.messages.delete(@message)
          #current_user.messages.push_with_attributes(@message, :from_id => misc.from_id, :to_id => misc.to_id, :box => misc.box, :is_read => 't')
          user_message = UserMessage.find(:first, :conditions => ["user_id = ? and message_id = ?", current_user.id, @message.id])
          user_message.is_read = 't'
          user_message.save!
        end
      end
    end
    @page_title = ' 消息'
  end
  
  def recvbox
    @messages = find_messages_by_box('r')
    @page_title = ' 消息'
  end
  
  def sendbox
    @sends = find_messages_by_box('s')
    @page_title = ' 消息'
  end
  
  def reply
    @user = User.find_by_login(params[:user][:id])
    @message = current_user.messages.find(:first, :conditions => ["messages.id = ?", params[:message][:id]])
    @message.title = reform_message_title @message.title
    @message.content = reform_message_content @user, @message.content
    render(:partial => "replyForm")
  end
  
  def cacel_reply
    render(:text => "")
  end
  
  private
  
  def delete_message(message)
    if !message.nil?
	    message.destroy if message.can_delete?
	    current_user.messages.delete(message)
	end
  end
  
  def reform_message_title(title)
    "re:" + title
  end
  
  def reform_message_content(user, content)
    "#{user.login}说:\n" + @message.content + "\n----------------------------------\n"
  end
  
  def unread_messages_num
    query = ""
    query << "select count(*) as num"
    query << " from messages, user_messages, users"
    query << " where messages.id = user_messages.message_id"
    query << " and user_messages.from_id = users.id"
    query << " and user_messages.is_read = 'f'"
    query << " and user_messages.user_id = '" 
    query << current_user.id.to_s
    query << "'"
    messages = Message.find_by_sql [query]
    messages[0].num
  end
  
  def find_messages_by_box(box)
    query = ""
    query << "select messages.*, user_messages.is_read, user_messages.box, users.login, users.nickname,"
    query << " user_messages.from_id, user_messages.to_id"
    query << " from messages, user_messages, users"
    query << " where messages.id = user_messages.message_id"
    if !box.nil?
      query << " and user_messages.box = '" 
      query << box
      query << "'"
      if box == 'r'
        query << " and user_messages.from_id = users.id"
      elsif box == 's'
        query << " and user_messages.to_id = users.id"
      end
    end
    query << " and user_messages.user_id = '" 
    query << current_user.id.to_s
    query << "' order by created_at desc"
    messages = Message.find_by_sql [query]
  end
  
  def find_message_by_id(id)
    query = ""
    query << "select messages.*, user_messages.is_read, user_messages.box, users.login, users.nickname,"
    query << " user_messages.from_id, user_messages.to_id"
    query << " from messages, user_messages, users"
    query << " where messages.id = user_messages.message_id"
    if !id.nil?
      query << " and messages.id = " 
      query << id
    end
    query << " and user_messages.to_id = users.id"
    query << " and user_messages.user_id = '" 
    query << current_user.id.to_s
    query << "' limit 1"
    messages = Message.find_by_sql [query]
    messages[0]
  end
end
